package com.rd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.dto.Result;
import com.rd.dto.ScrollResult;
import com.rd.dto.UserDTO;
import com.rd.entity.Blog;

import com.rd.entity.Follow;
import com.rd.entity.User;
import com.rd.mapper.BlogMapper;
import com.rd.service.BlogService;
import com.rd.service.FollowService;
import com.rd.service.UserService;
import com.rd.utils.SystemConstants;
import com.rd.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static com.rd.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.rd.utils.RedisConstants.FEED_KEY;

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    @Resource
    UserService userService;

    @Resource
    FollowService followService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    BlogService blogService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);

    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return; // 用户未登录，无需查询是否点赞
        }
        Long userId = user.getId();
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);

    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 查询与此blog有关的用户
        queryBlogUser(blog);

        //查询此blog有没有被点赞
        isBlogLiked(blog);

        return Result.ok(blog);
    }


    @Override
    public Result likeBlog(Long id) {
        // 获取用户信息
        Long userId = UserHolder.getUser().getId();
        System.out.println("userId:"+userId);
        String key = BLOG_LIKED_KEY + id;

        // 判断用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){
            // 未点赞，点赞 +1
            boolean liked = update().setSql("liked = liked + 1").eq("id", id).update();
            if (liked){
                //将点赞用户添加到zset集合, 时间戳为点赞时间顺序
               stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
            }
        }else{
            // 已点赞，取消点赞
            boolean liked = update().setSql("liked = liked - 1").eq("id", id).update();
            if (liked){
                // 移除set集合中的点赞用户
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {

        String key = BLOG_LIKED_KEY + id;
        // 查询点赞的top5用户 range key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 获取 top5 集合中的所有id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String sids = StrUtil.join(",", ids);

        // TODO 根据id查询用户
        // in 查询的记录不是指定输入输出
//        List<UserDTO> userList = userService.listByIds(ids)
//                .stream()
//                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
//                .collect(Collectors.toList());

        // where id in(5,1) order by field(id,5,1)
        // 使in按照指定输入输出
        List<UserDTO> userList = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + sids + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userList);
    }

    // 发布笔记
    @Override
    public Result saveBlog(Blog blog) {

        UserDTO userDTO = UserHolder.getUser();
        blog.setUserId(userDTO.getId());
        // 保存新增笔记
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败!");
        }
        // 查询up的所有粉丝   select * from tb_follow where follow_user_id = user_id
        List<Follow> follows = followService.query().eq("follow_user_id", userDTO.getId()).list();

        for (Follow follow: follows) {
            // 获取粉丝id
            Long userId = follow.getUserId();
            // 4.2.推送
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    // 查询关注up发布的笔记   offset为跳过元素的个数
    @Override
    public Result queryBlogOfFollow(Long lastId, Integer offset) {

        //获取当前用户
        Long userId = UserHolder.getUser().getId();

        String key = FEED_KEY + userId;
        //查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, lastId, offset, 3);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //解析数据 blogId，minTime，offset
        long minTime = 0;
        int count = 1;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue(); //最后一个元素值最小
            if (time == minTime){
                count++;
            }else{
                minTime = time;
                count = 1;
            }
        }
        String sids = StrUtil.join(",", ids);
        //根据id查询blog
        List<Blog> blogs = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + sids + ")").list();

        for (Blog blog : blogs) {
            // 查询与此blog有关的用户
            queryBlogUser(blog);

            //查询此blog有没有被点赞
            isBlogLiked(blog);
        }

        //封装并返回
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(count);
        result.setMinTime(minTime);

        return Result.ok(result);
    }
}
